<template>
  <img
    v-lazy="src"
    :alt="alt"
    :class="className"
    @load="handleLoad"
  />
</template>

<script>
export default {
  name: 'LazyImage',
  props: {
    src: {
      type: String,
      required: true
    },
    alt: {
      type: String,
      default: ''
    },
    className: {
      type: String,
      default: ''
    }
  },
  directives: {
    lazy: {
      mounted(el) {
        function loadImage() {
          const imageElement = el;
          imageElement.src = imageElement.dataset.src;
        }
        function handleIntersect(entries, observer) {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              loadImage();
              observer.unobserve(el);
            }
          });
        }
        function createObserver() {
          const options = {
            root: null,
            threshold: '0'
          };
          const observer = new IntersectionObserver(handleIntersect, options);
          observer.observe(el);
        }
        if ('IntersectionObserver' in window) {
          createObserver();
        } else {
          loadImage();
        }
      }
    }
  },
  methods: {
    handleLoad() {
      this.$emit('load');
    }
  }
}
</script>

<style scoped>
img {
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
}

img[src] {
  opacity: 1;
}
</style> 